<template>
    <div class="">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-message"></i>&nbsp;编辑商品</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div style="max-width:1000px;padding:10px 0 30px 0px">
                <el-alert
                    title="建议上传的图片压缩之后再上传，便于APP请求图片资源加载速度快"
                    type="warning"
                    show-icon>
                </el-alert>
            </div>
            <el-form ref="form" label-width="160px">
                <el-form-item label="商品封面图：">
                    <div class="sola-upload clearfix">
                        <div class="sola-left clearfix" v-show="bannerPicture.length>0">
                            <div v-for="(item, index) in bannerPicture" class="sola-flex" :key="index">
                                <img  :src="item" />
                                <span class="delete" @click="delPicture(index,item,1)"><i class="el-alert__icon el-icon-error"></i></span>
                            </div>
                        </div>
                        <div class="sola-file-box">
                            <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                            <input class="btn-file" type="file" @change="uploadBanner" v-loading.fullscreen.lock="fullscreenLoading"/>
                            <span style="color:red;padding-left:10px;">最多上传五张，(比例规范 宽大于750)建议上传的轮播图比例是1：1 示例750X750 </span>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="商品名称：">
                    <el-input v-model="goodsName" placeholder="请输入商品名称" style="width:600px"></el-input>
                </el-form-item>
                <el-form-item label="商品副标题：">
                    <el-input v-model="title" placeholder="请输入商品标题" style="width:600px"></el-input>
                </el-form-item>
                <el-form-item label="退换类型：">
                    <el-radio v-model="refundType" label="1" border >可退可换</el-radio>
                    <el-radio v-model="refundType" label="2" border>可退不换</el-radio>
                    <el-radio v-model="refundType" label="3" border>不可退可换</el-radio>
                    <el-radio v-model="refundType" label="4" border>不退不换</el-radio>
                </el-form-item>
                <el-form-item label="发货时间(小时)：">
                    <el-input v-model="deliveryTime" type="number" placeholder="请输入多少小时发货" style="width:200px"></el-input>
                </el-form-item>
                <el-form-item label="满多少包邮：">
                    <el-input v-model="freeShipping" type="number" placeholder="请输入满多少包邮价格" style="width:200px"></el-input>
                </el-form-item>
                <el-form-item label="运费：">
                    <el-input v-model="freightMoney" type="number" placeholder="请输入运费" style="width:200px"></el-input>
                </el-form-item>
                <el-form-item label="商品规格信息：">
                    <div class="clearfix">
                        <div v-for="(item,index) in skuProp" style="padding-bottom:10px;" :key="index">
                            <el-input v-model="item.spec"  placeholder="请输入规格名称" style="width:160px" clearable></el-input>
                            <el-input v-model="item.original_price" type="number" placeholder="请输入规格原价" style="width:160px"></el-input>
                            <el-input v-model="item.price" type="number" placeholder="请输入规格优惠价" style="width:160px"></el-input>
                            <el-input v-model="item.stock" type="number" placeholder="请输入规格库存数" style="width:160px"></el-input>
                            <el-button type="danger" icon="el-icon-delete" @click="delGoodsSku(item,index)"></el-button>
                        </div>
                        <div style="padding-top:5px;">
                            <el-button type="primary" plain @click="addGoodsSku"><i class="el-icon-plus"></i>&nbsp;&nbsp;新增规格信息</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="商品详情图：">
                    <div class="sola-upload clearfix">
                        <div class="sola-left clearfix" v-show="detailPicture.length>0">
                            <div v-for="(item, index) in detailPicture" class="sola-flex" :key="index">
                                <img  :src="item" />
                                <span class="delete" @click="delPicture(index,item,2)"><i class="el-alert__icon el-icon-error"></i></span>
                            </div>
                            
                        </div>
                        <div class="sola-file-box">
                            <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                            <input class="btn-file" type="file" accept="image/*" @change="uploadDetail" v-loading.fullscreen.lock="fullscreenLoading"/>
                            <span style="color:red;padding-left:10px;">项目说明、项目规则、拼团说明、拼团规则、商品详情图宽度750*自适应（高度不限制）</span>
                        </div>
                    </div>
                </el-form-item>
                
                <el-form-item>
                    <el-button type="primary" @click="onAddGoods">确认编辑</el-button>
                    <el-button  @click="returnList">返回列表</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import {postUploadBase64} from '@/api/public'
import { getcGoodDetails,postGoodEdit,postspecIdDelete} from "@/api/goods/goods";
export default {
    name:"goodsList",
    data() {
        return {
            goodsId:0,
            fullscreenLoading:false,
            idx:0,//当前记录的下标
            spec_id:0,//删除规格下标
            delVisible:false,
            accept: 'image/gif, image/jpeg, image/png, image/jpg', //图片上传类型
            typeId:'', //当前要删除图片的类型   1封面图 2详情图
            bannerPicture:[],//存放的商品轮播图
            detailPicture:[],//存放的商品详情图
            goodsName:'', //商品名称
            title:'',//商品标题
            deliveryTime:'',
            freeShipping:'',
            freightMoney:'',
            refundType:'1', //退换类型：1可退可换、2可退不换、3不可退可换、4不退不换
            skuProp:[{spec_id:0,spec:'',price:"",original_price:"",stock:""}],//规格、原价、优惠价、sku
        }
    },
    //实例创建
    created(){
        //获取商品的分类
        // this.getGoodsClassify();
        if(this.$route.query.goodsId&&this.$route.query.goodsId!=""){
            this.goodsId = this.$route.query.goodsId;
            this.getGoodsInfo();
        }
    },
    //计算属性
    computed:{

    },
    //方法
    methods: {
        getGoodsInfo(){
            getcGoodDetails(this.goodsId).then(response=>{
                // console.log(response);
                if(response.code==200){
                    var data = response.data;
                    this.freeShipping = data.free_shipping;
                    this.freightMoney = data.freight_money;
                    this.deliveryTime = data.delivery_time;
                    this.refundType = data.refund_type+"";
                    this.goodsName = data.goods_name;
                    this.title = data.goods_title;
                    var specList = data.specList;
                    var array =[];
                    //skuProp:[{spec:'',price:"",original_price:"",stock:""}],//规格、原价、优惠价、sku
                    specList.forEach(item=>{
                        var obj = {};
                        obj.spec_id = item.id;
                        obj.spec = item.spec;
                        obj.price = item.price;
                        obj.original_price = item.original_price;
                        obj.stock = item.stock;
                        array.push(obj);
                    });
                    this.skuProp =array;
                    this.bannerPicture =JSON.parse(data.banner_img);
                    this.detailPicture = JSON.parse(data.goods_detail);
                }else{
                    this.$notify.error({
                        title: '异常',
                        duration:2000,
                        message: '失败原因：'+response.msg
                    });
                }
            })
        },
        returnList(){
            this.$router.push('/goods/list');
        },
        //确定删除图片
        deleteRow(){
            if(this.typeId==1){
                //封面图
                this.bannerPicture.splice(this.idx,1);
                this.$message.success('删除成功');
            }else if(this.typeId==2){
                //详情图
                this.detailPicture.splice(this.idx,1);
                this.$message.success('删除成功');
            }else if(this.typeId==3){
                //删除规格信息  根据数组下标删除信息
                this.skuProp.splice(this.idx,1);
                if(this.spec_id>0){
                    this.delGoodsSpec();
                }else{
                    this.$message.success('删除成功');
                }
                
            }
            //console.log(this.bannerPicture)
            // this.tableData.splice(this.idx,1);
            this.delVisible = false;
        },
        //删除图片
        delPicture(index, row,typeId){
            //当前记录的下标
            this.idx = index;
            this.typeId = typeId;
            this.delVisible = true;
            
        },
        //触发项目封面图 file
        uploadBanner(event){
            var _event = event;
            var _this = this;
            let reader =new FileReader();  
            let img1=event.target.files[0];  
            let type=img1.type;//文件的类型，判断是否是图片  
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;  
            if(this.accept.indexOf(type) == -1){  
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;  
            }  
            else if(size>3145728){  
                this.$message({
                    message: '请选择3M以内的图片上传',
                    type: 'warning'
                }); 
                return false;  
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                this.fullscreenLoading = true;
                let reader = new FileReader();
                reader.readAsDataURL(img1);
                reader.onload = function(e) {
                    var base = this.result;
                    
                    postUploadBase64(base).then(response=>{
                        // console.log(response);
                        if(response.code==200){
                            _this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            _this.bannerPicture.push(response.data);
                            
                        }else{
                            _this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.msg
                            });
                        }
                        setTimeout(function(){
                            _this.fullscreenLoading = false;
                        },500);
                    })
                }
                
            }
        },
        //触发商品详情图 file 
        uploadDetail(file){
            var _event = event;
            var _this = this;
            let reader =new FileReader();  
            let img1=event.target.files[0];  
            let type=img1.type;//文件的类型，判断是否是图片  
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;  
            if(this.accept.indexOf(type) == -1){  
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;  
            }  
            else if(size>3145728){  
                this.$message({
                    message: '请选择3M以内的图片上传',
                    type: 'warning'
                }); 
                return false;  
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                this.fullscreenLoading = true;
                let reader = new FileReader();
                reader.readAsDataURL(img1);
                reader.onload = function(e) {
                    var base = this.result;
                    postUploadBase64(base).then(response=>{
                        // console.log(response);
                        if(response.code==200){
                            _this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            _this.detailPicture.push(response.data);
                            
                        }else{
                            _this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.msg
                            });
                        }
                        setTimeout(function(){
                            _this.fullscreenLoading = false;
                        },500);
                        
                    })
                    
                }
            }
        },
        //获取项目的
        handleChange(){
        },
        //删除商品规格信息
        delGoodsSku(item,index){
            if(this.skuProp.length<=1){
                this.$notify({title: '警告',message: '规格信息至少要填一项',type: 'warning'});
            }else{
                console.log(item)
                this.idx = index;
                this.typeId = 3;
                this.spec_id = item.spec_id;
                this.delVisible = true;
            }
        },
        //delGoodsSpec
        delGoodsSpec(){
            var _this = this;
            postspecIdDelete(this.spec_id).then(response=>{
                if(response.code==200){
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                }else{
                    this.$notify.error({
                        title: '删除失败',
                        duration:2000,
                        message: '失败原因：'+response.msg
                    });
                }
            })
        },
        //新增商品规格信息
        addGoodsSku(){
            var object = {spec_id:0,spec:'',price:"",original_price:"",stock:""};
            this.skuProp.push(object);
        },
        //校验规格
        toptipSkuFlag(){
            var flag = false;
            var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
            var  stockReg= /^\+?[1-9][0-9]*$/;
            // console.log(this.skuProp)
            this.skuProp.forEach((item)=>{
                if(item.spec==""){
                    this.$notify.info({title: '提示',message: '请填写商品规格'});
                    flag = true;
                    return false;//跳出循环
                }else if(item.price===""){
                    this.$notify.info({title: '提示',message: '请填写商品规格原价'});
                    flag = true;
                    return false;//跳出循环
                }else if(!reg.test(item.price)){
                    this.$notify.info({title: '提示',message: '请填写正确的商品规格原价,且金额最多两位小数点'});
                    flag = true;
                    return false;//跳出循环
                    
                }else if(parseFloat(item.price)<0){
                    this.$notify.info({title: '提示',message: '商品规格原价至少要大于零'});
                    flag = true;
                    return false;//跳出循环
                }else if(item.original_price==""){
                    flag = true;
                    this.$notify.info({title: '提示',message: '请填写商品规格优惠价'});
                    return false;//跳出循环
                }else if(!reg.test(item.original_price)){
                    flag = true;
                    this.$notify.info({title: '提示',message: '请填写正确的商品规格优惠价,且金额最多两位小数点'});
                    return false;//跳出循环
                }else if(item.stock==""){
                    flag = true;
                    this.$notify.info({title: '提示',message: '请填写商品规格库存数'});
                    return false;//跳出循环
                }else if(parseInt(item.stock)=="NaN"){
                    flag = true;
                    this.$notify.info({title: '提示',message: '规格库存数只能是数字类型'});
                    return false;//跳出循环
                }else if(!stockReg.test(item.stock) && item.stock!="0"){
                    flag = true;
                    this.$notify.info({title: '提示',message: '规格库存数是正整数'});
                    return false;//跳出循环
                }
            });
            return flag;
        },
        //确认新增商品
        onAddGoods(){
            if(this.goodsName==""){
                this.$notify.info({title: '提示',message: '请填写商品名称'});
                return false;
            }
            else if(this.bannerPicture.length<1){
                this.$notify.info({title: '提示',message: '请先上传商品封面图'});
                return false;
            }else if(this.title==""){
                this.$notify.info({title: '提示',message: '请填写商品副标题'});
                return false;
            }
            else if(this.deliveryTime==""){
                this.$notify.info({title: '提示',message: '请填写发货时间（小时）单位'});
                return false;
            }else if(this.freeShipping==""){
                this.$notify.info({title: '提示',message: '请填写满多少包邮'});
                return false;
            }else if(this.freightMoney==""){
                this.$notify.info({title: '提示',message: '请填写运费'});
                return false;
            }
            else if(this.toptipSkuFlag()){}
            else if(this.detailPicture.length<1){
                this.$notify.info({title: '提示',message: '请上传商品的详情图'});
                return false;
            }
            else{
                let param ={}
                param.goodsId = this.goodsId,//商品Id
                param.goodsName = this.goodsName;//商品名称
                param.title=this.title,//商品副标题
                param.deliveryTime= this.deliveryTime;//发货时间：小时
                param.freeShipping= this.freeShipping;//满多少包邮
                param.freightMoney = this.freightMoney;//运费
                param.refundType = this.refundType;//退换类型
                param.headImg = this.bannerPicture[0];//封面图
                param.bannerImg=JSON.stringify(this.bannerPicture), // 封面图  图片，数组JSON字符串
                param.detail=JSON.stringify(this.detailPicture),//详情，数组JSON字符串
                this.skuProp.forEach((value)=>{
                    // object = {spec:'',price:"",original_price:"",stock:""};
                    value.original_price =parseFloat(value.original_price);//优惠价
                    value.price =parseFloat(value.price); //原价
                    value.stock =parseInt(value.stock);  //修改类型  整数类型
                });
                param.specJson=JSON.stringify(this.skuProp)//商品规格列表，数组JSON字符串，格式：[{"spec": "100g", "price": 200, "original_price": 180, "stock": 99}]

                //调用提交方法
                // console.log(param)
                this.saveGoods(param);
            }
        },
        //提交商品信息上传
        saveGoods(param){
            var _this =this;
            postGoodEdit(param).then(response=>{
                // console.log(response);
                if(response.code==200){
                    this.$message({
                        message: '恭喜你，编辑成功',
                        type: 'success'
                    });
                    setTimeout(function(){
                        _this.$router.push('/goods/list');
                        // this.$router.push({path:''})
                    },1500);
                }else{
                    this.$notify.error({
                        title: '编辑失败',
                        duration:2000,
                        message: '失败原因：'+response.msg
                    });
                }
            });
            
        }
    }
}
</script>
<style lang="stylus" scoped>
    .el-form-item .el-cascader{
        width :400px;
    }
    .el-cascader-menus .el-cascader-menu{
        width :240px
    }
    .sola-upload{
        .sola-left{
            width :100%;
            height :auto;
            .sola-flex{
                float:left
                width: 360px;
                height: 180px;
                margin-bottom 20px;
                margin-right:15px;
                position:relative;
                .delete{
                    position:absolute;
                    top:2px;
                    right:13px;
                    color: #f56c6c;
                    display:inline-block;
                    padding:5px 5px;
                    .el-alert__icon{font-size:28px;cursor:pointer}
                }
                img {
                    width:100%;
                    height:100%;
                }
            }
        }
        .sola-file-box{
            
            position:relative;
            .btn-file{
                position:absolute;
                top:0;
                left:0;
                z-index 1;
                opacity:0;
                width :120px;
                height :40px;
                outline: 0;
                background-color :none;
                cursor:pointer;
            }
        }

    }
</style>


